//controllers.depthfirst.Agent.java
package controllers.depthfirst;

import java.awt.Graphics2D;
import java.util.ArrayList;
import java.util.Random;

import core.game.Observation;
import core.game.StateObservation;
import core.player.AbstractPlayer;
import ontology.Types;
import tools.ElapsedCpuTimer;

public class Agent extends AbstractPlayer{
    protected ArrayList<Observation> grid[][];
    protected int block_size;
    protected ArrayList<Types.ACTIONS> path = new ArrayList<Types.ACTIONS>();
    protected ArrayList<StateObservation> explored = new ArrayList<StateObservation>();
    protected boolean found = false;


    public Agent(StateObservation so, ElapsedCpuTimer elapsedTimer)
    {
        grid = so.getObservationGrid();
        block_size = so.getBlockSize();
//        depthfirst(so);
    }

    public int depthfirst(StateObservation stateObs)
    {
        if (stateObs.isGameOver())
        {
            if (stateObs.getGameWinner()==Types.WINNER.PLAYER_LOSES) return -1;
            else return 0;
        }
        else
        {
            for (int index = 0; index<explored.size(); index++)
            {
                if (stateObs.equalPosition(explored.get(index))) return -1;
            }
//            if (explored.contains(stateObs)) return -1;
            explored.add(stateObs);
            Types.ACTIONS action = null;
            ArrayList<Types.ACTIONS> actions = stateObs.getAvailableActions();
            if (actions.size() == 0) return -1;
            for (int index = 0; index < actions.size(); index++) {
                action = actions.get(index);
                StateObservation stCopy = stateObs.copy();
                stCopy.advance(action);
                int flag = depthfirst(stCopy);
                if (flag==0)
                {
                    path.add(action);
                    return 0;
                }
                else continue;
            }
            return -1;
        }
    }

    public Types.ACTIONS act(StateObservation stateObs, ElapsedCpuTimer elapsedTimer)
    {
        if (!found) {
            depthfirst(stateObs);
            found = true;
        }
        Types.ACTIONS action = path.get(path.size()-1);
        path.remove(path.size()-1);
        return action;
    }
}
